package com.yq.ylmall.product.utils;

import cn.hutool.core.bean.BeanUtil;
import com.yq.ylmall.model.product.Category;
import com.yq.ylmall.vo.product.CategoryVo;

import java.util.ArrayList;
import java.util.List;

/**
 * 分类多级菜单处理
 */
public class CategoryHelper {

    /**
     * 使用递归方法建菜单
     * @param categoryList List<Category>
     * @return List<Category>
     */
    public static List<CategoryVo> buildTree(List<Category> categoryList) {
        List<CategoryVo> trees = new ArrayList<>();
        for (Category category : categoryList) {
            if (category.getParentId() != null && category.getParentId() == 0) {
                trees.add(findChildren(category, categoryList));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     * @param category {@link Category}
     * @param treeNodes List<Category>
     * @return {@link Category}
     */
    public static CategoryVo findChildren(Category category, List<Category> treeNodes) {
        category.setChildren(new ArrayList<>());
        for (Category it : treeNodes) {
            if (category.getParentId() != null && (category.getId().longValue() == it.getParentId().longValue())) {
                category.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return BeanUtil.copyProperties(category, CategoryVo.class);
    }
}
